package util;


import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBUtils {
    private static volatile MysqlDataSource mysqlDataSource;
    //private static volatile Connection connection;

    private static MysqlDataSource getMysqlDataSource(){
        if(mysqlDataSource == null)
        {
            synchronized (DBUtils.class)
            {
                if(mysqlDataSource == null)
                {
                    mysqlDataSource = new MysqlDataSource();
                    mysqlDataSource.setURL("jdbc:mysql://127.0.0.1:3306/myblog2022?characterEncoding=utf8&useSSL=false");
//                    mysqlDataSource.setURL("jdbc:mysql://43.142.44.34:3306/myblog2022?characterEncoding=utf8&useSSL=false");
                    mysqlDataSource.setUser("root");
                    mysqlDataSource.setPassword("12345678");
                }
            }
        }
        return mysqlDataSource;
    }

    /**
     * 可以单例模式,可以多例模式,这里是多例（谁调用就创建一个）
     * 并发量比较高的时候多例模式性能更高
     * @return
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        Connection connection = (Connection) getMysqlDataSource().getConnection();
        return connection;
    }


    /**
     * 关闭资源
     * @param resultSet
     * @param statement
     * @param connection
     * @throws SQLException
     */
    public static void close(ResultSet resultSet , PreparedStatement statement , Connection connection) throws SQLException {
        if(resultSet != null)
        {
            resultSet.close();
        }
        if(statement != null)
        {
            statement.close();
        }
        if(connection != null)
        {
            connection.close();
        }
    }
}
